// 模块化路由
const express = require('express');
const router = express.Router();

// 引入模块
const svg = require('svg-captcha');
const myquery = require('./myquery');

// 接收post提交的参数
router.use(express.urlencoded({ extended: false }));

// 登录
router.post('/login', async (req, res, next) => {
    let { username, password } = req.body;
    if (!username || !password) {
        next({ code: 400, msg: '请输入有效内容' });
        return;
    }
    let [err, result] = await myquery(`select * from user where username='${username}' and password='${password}'`);
    if (err) {
        next(err);
        return;
    }
    if (result.length == 0) {
        next({ code: 400, msg: '账号或密码错误' });

    }
    else {
        res.send({ code: 200, msg: '登录成功' });
    }
})

// 注册
router.post('/register', async (req, res, next) => {
    let { username, password, password2 } = req.body;
    if (!username || !password || !password2) {
        next({ code: 400, msg: '请输入有效内容' });
        return;
    }
    if (password != password2) {
        next({ code: 400, msg: '两次密码不一致' });
        return;
    }
    let [err1, result1] = await myquery(`select * from user where username='${username}'`);
    if (err1) {
        next(err1);
        return;
    }
    if (result1.length != 0) {
        next({ code: 400, msg: '该用户已注册' });
        return;
    }
    let [err2, result2] = await myquery(`insert into user (username,password) values ('${username}','${password}')`);
    if (err2) {
        next(err2);
    }
    if (result2.affectedRows != 0) {
        res.send({ code: 200, msg: '注册成功' });
    }
    else {
        next({ code: 500, msg: '请稍后重试' });
    }
})

// 暴露
module.exports = router;